package com.skyline.jfs.base.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.skyline.jfs.base.model.Administrator;
import com.skyline.jfs.base.service.AdminBasicService;
import com.skyline.jfs.common.config.Config;

@Controller
@RequestMapping(value = "/admin/")
public class AdminBasicController {
	@Autowired
	private AdminBasicService adminBasicService;

	@RequestMapping(value = "login.html", method = RequestMethod.GET)
	public String loginRequest() {
		return "admin/login";
	}

	@RequestMapping(value = "login.html", method = RequestMethod.POST)
	public String loginExecute(@RequestParam("jobNum") Long jobNum,
			@RequestParam("password") String password,
			HttpServletRequest request) {
		HttpSession session = request.getSession();
		try {
			System.out.println(jobNum + ":" + password);
			Administrator a = adminBasicService.login(jobNum, password);
			session.setAttribute("administrator", a);
			return "admin/adminWelcome";
		} catch (Exception e) {
			String message = Config
					.getMessage("AdminBasicController.jobNumOrPasswordWrong");
			request.setAttribute("message", message);
			return "admin/login";
		}
		// /return null;
	}

	@RequestMapping(value = "logout.html", method = RequestMethod.GET)
	public String Logout(HttpSession session, HttpServletRequest request) {
		session.invalidate();
		String message = Config
				.getMessage("AdminBasicController.logoutSuccess");
		request.setAttribute("message", message);
		return "admin/login";
	}
	
	@RequestMapping(value = "clusterAdmins.html", method = RequestMethod.GET)
	public String getAllAdministrator(HttpSession session,
			HttpServletRequest request) {
		if (session.getAttribute("administrator") == null) {
			return "admin/login";
		}
		List<Administrator> administrators = adminBasicService.getAll();
		request.setAttribute("administrators", administrators);
		return "admin/clusterAdmins";
	}

}
